/** drop target **/
var _target = document.getElementById('drop');

/** Spinner **/
var spinner;

var _workstart = function() { spinner = new Spinner().spin(_target); }
var _workend = function() { spinner.stop(); }

/** Alerts **/
var _badfile = function() {
  alertify.alert('This file does not appear to be a valid Excel file.  If we made a mistake, please send this file to <a href="mailto:dev@sheetjs.com?subject=I+broke+your+stuff">dev@sheetjs.com</a> so we can take a look.', function(){});
};

var _pending = function() {
  alertify.alert('Please wait until the current file is processed.', function(){});
};

var _large = function(len, cb) {
  alertify.confirm("This file is " + len + " bytes and may take a few moments.  Your browser may lock up during this process.  Shall we play?", cb);
};

var _failed = function(e) {
  console.log(e, e.stack);
  alertify.alert('We unfortunately dropped the ball here.  We noticed some issues with the grid recently, so please test the file using the <a href="/js-xlsx/">raw parser</a>.  If there are issues with the file processor, please send this file to <a href="mailto:dev@sheetjs.com?subject=I+broke+your+stuff">dev@sheetjs.com</a> so we can make things right.', function(){});
};

/** Handsontable magic **/
var boldRenderer = function (instance, td, row, col, prop, value, cellProperties) {
  Handsontable.TextCell.renderer.apply(this, arguments);
  $(td).css({'font-weight': 'bold'});
};

var $container, $parent, $window, availableWidth, availableHeight;
var calculateSize = function () {
  var offset = $container.offset();
  availableWidth = Math.max($window.width() - 250,600);
  availableHeight = Math.max($window.height() - 250, 400);
};

$(document).ready(function() {
  $container = $("#hot"); $parent = $container.parent();
  $window = $(window);
  $window.on('resize', calculateSize);
});

/* make the buttons for the sheets */
var make_buttons = function(sheetnames, cb) {
  var $buttons = $('#buttons');
  $buttons.html("");
//  $buttons.addClass("btn btn-default");
  sheetnames.forEach(function(s,idx) {
    var button= $('<button/>').attr({ type:'button', name:'btn' +idx, text:s ,class:'btn btn-success'});
    button.append('<h3>' + s + '</h3>');
    button.click(function() { cb(idx); });
    $buttons.append(button);
  });
};

var fileName;
function printName(name){
	//console.log(name);
	fileName = name;
}

var _onsheet = function(json, sheetnames, select_sheet_cb) {
	
  $('#footnote').hide();

  make_buttons(sheetnames, select_sheet_cb);
  calculateSize();

  /* add header row for table */
  if(!json) json = [];
	json.forEach(function(r) { if(json[0].length < r.length) json[0].length = r.length; });
  calculateSize();
  /* showtime! */
  $("#hot").handsontable({
    data: json,
    startRows: 5,
    startCols: 3,
    stretchH: 'all',
    rowHeaders: true,
    colHeaders: true,
    width: function () { return availableWidth; },
    height: function () { return availableHeight; },
    stretchH: 'all'
  });
  
  for(var i =0;i<fileName.length;i++){
		if(fileName[i]=="."){
			fileName=fileName.substring(0,i);
		}
	}

  $("#upload").on('click',json,function(){
		
		for(var i=0;i<json.length;i++){
			//删除空的数据行
	  		if(json[i].length==0){
	  			json.splice(i,1);
	  			i=i-1;
	  		}
	  		else{
	  			//每一行不存在数据或者数据为“”的赋值为null，保证每行length相同
	  			for(var j=0;j<json[0].length;j++){
		  			if(json[i][j] === undefined || json[i][j] ===""){
		  				json[i][j] = null;
		  			}
		  		}
	  		}
	  	}
	  	var tableName = $('#selectT option:selected').val();
	  	var driverClass = $('#className').val();
		var baseUrl = $('#baseUrl').val();
		var username = $('#username').val();
		var password = $('#password').val();
		var params = {
				excelData:json,
				tableName: tableName,
	  			driverClass : driverClass,
	  			baseUrl:baseUrl,
				username:username,
				password:password
		}
		var url = 'http://localhost:8080/drexcel/loadData.action';
		$.ajax({
			method:'POST',
			url:encodeURI(url),
			data:JSON.stringify(params),
			datatype:'json',
			contentType: 'application/json',
            scriptCharset: 'utf-8',
			success:function(data){
				
			}
		})
	})	

};

/** Drop it like it's hot **/
DropSheet({
  drop: _target,
  on: {
    workstart: _workstart,
    workend: _workend,
    sheet: _onsheet,
    foo: 'bar'
  },
  errors: {
    badfile: _badfile,
    pending: _pending,
    failed: _failed,
    large: _large,
    foo: 'bar'
  }
})




/**
 * 提交按钮提交json中的数据
 */

/**
 *		数据库连接信息 
 * */

$('#dsbtn').on('click',function(){
	$('#myModal').modal('toggle');
	$('#baseUrl').val(""),
	$('#username').val(""),
	$('#password').val(""),
	$('#afconn').on('click',function(){
		var driverClass = $('#className').val();
		var baseUrl = $('#baseUrl').val();
		var username = $('#username').val();
		var password = $('#password').val();
		var url = 'http://localhost:8080/drexcel/connParams.action?driverClass='+driverClass+'&baseUrl='+ baseUrl + '&username=' + username + '&password=' + password;
		$.ajax({
			method:'GET',
			url : encodeURI(url),
			dataType : 'json',
			success : function(data){
				$('#myModal').modal('toggle');
				if(data.success == "success")
				$('#Constatus').val("连接成功");
				var optionstr="";
				if(data.tableName.length>0){
					 for(var i=0,len=data.tableName.length;i<len;i++){
					        optionstr+="<option>"+data.tableName[i]+"</option>";
					     }
					 $("#selectT").append(optionstr);
				}
			}
		})
	})
})



/**
 *		数据库建表信息 
 * */
$(document).on('click','#ctbtn',function(){
	$('#myModal1').modal('toggle');
	$('#afcreateTable').on('click',function(){
		var tableSql = $('#tableSql').val();
		var driverClass = $('#className').val();
		var baseUrl = $('#baseUrl').val();
		var username = $('#username').val();
		var password = $('#password').val();
		var url = 'http://localhost:8080/drexcel/createTable.action';
		$.ajax({
			method: 'post',
			url: encodeURI(url),
			data:{
				tableSql:tableSql,
				driverClass:driverClass,
				baseUrl:baseUrl,
				username:username,
				password:password
			},
			dataType: 'json',
			success: function(data){
				if(data.success == "success"){
					$('#myModal1').modal('toggle');
					$('#tableSql').val("");
					$("#selectT").empty();
					var url ='http://localhost:8080/drexcel/connParams.action?driverClass='+driverClass+'&baseUrl='+ baseUrl + '&username=' + username + '&password=' + password;
					$.ajax({
						method:'GET',
						url:encodeURI(url),
						success:function(data){
							var optionstr="";
							if(data.tableName.length>0){
								 for(var i=0,len=data.tableName.length;i<len;i++){
									 optionstr+="<option>"+data.tableName[i]+"</option>";
								     }
								 $("#selectT").append(optionstr);
							}
						}
					})
				}else{
					alert("false")
				}
			}
		})
	})
})










